<template>
  <!-- 下拉菜单 -->
  <div class="dropdown" ref="dropdownRef">
    <a
      href="#"
      class="btn btn-outline-light my-2 dropdown-toggle"
      @click.prevent="toggleOpen"
      >{{ title }}</a
    >
    <ul class="dropdown-menu" :style="{ display: 'block' }" v-if="isOpen">
      <!-- 占位 -->
      <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import useClickOutside from "../hooks/useClickOutside";
export default defineComponent({
  props: {
    title: {
      type: String,
      required: true,
    }
  },
  setup() {
    //默认刚打开页面隐藏下拉菜单
    const isOpen = ref(false)
    //点击其他区域下拉菜单自动隐藏
    const dropdownRef = ref<null | HTMLElement>(null)
    //进行点击下拉列表的显示
    const toggleOpen = () => {
        isOpen.value = !isOpen.value
    }
    const isClickOutSide = useClickOutside(dropdownRef)
    watch(isClickOutSide,() => {
        if(isOpen.value && isClickOutSide.value) {
            isOpen.value = false
        }
    })
    return {
        isOpen,
        toggleOpen,
        dropdownRef
    }
  }
});
</script>
